package org.sunsys.qa.web.command;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.sunsys.qa.service.response.Response;
import org.sunsys.qa.service.response.ResponseStatus;
import org.sunsys.qa.service.response.UserRegistrationResponse;
import org.sunsys.qa.service.user.UserRegistrationService;
import org.sunsys.qa.user.UserRegistrationDto;

public class UserRegistrationCommand implements QaWebCommand {

	@Override
	public Response execute(HttpServletRequest request, HttpServletResponse response) {
		
		
		/*  extract the User Registration properties from request object */
		String userName = request.getParameter("userName");
		String userId = request.getParameter("userId");
		String password = request.getParameter("password");
		String dateOfBirthStr = request.getParameter("dob");
		String mailId = request.getParameter("mailId");
		
		//TODO have to validate the fields retrieved from web page
		UserRegistrationService userRegistrationService = new UserRegistrationService();
		
		UserRegistrationDto registrationDto = new UserRegistrationDto();
		
		registrationDto.setUserName(userName);
		registrationDto.setUserId(userId);
		registrationDto.setPassword(password);
		registrationDto.setMailId(mailId);
		
		DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
		Date dateOfBirth = null;
		try {
			dateOfBirth = df.parse(dateOfBirthStr);
		}catch(ParseException e1) {
			//TODO handle
		}
		registrationDto.setDateOfBirth(dateOfBirth);
		registrationDto.setDateOfRegistration(new Date());
		/* nullify the date of birth string */
		dateOfBirthStr = null;
		
		/* register the user with the help of User Registration controller */
		UserRegistrationResponse userRegistrationResponse = userRegistrationService.service(registrationDto);
		
		/* depending on the User Registration Status, redirect to the respective view */
		
		if(userRegistrationResponse.getStatus()== ResponseStatus.SUCCESS) {
			//redirect to Success page
		} else {
			//redirect to Success failure page
		}
		
		return userRegistrationResponse;
	}
}
